package com.efounder.zone.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.activity.ViewPagerActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.model.UserEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.RoundImageView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.language.MultiLanguageUtil;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.CircleImageView;
import com.efounder.zone.R;
import com.efounder.zone.activity.MobileZoneDetailActivity;
import com.efounder.zone.activity.ZoneMessageActivity;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.commentview.CommentListView;
import com.efounder.zone.commentview.ZoneCommentBean;
import com.efounder.zone.util.CommentUtil;
import com.efounder.zone.util.ZoneTimeUtil;
import com.efounder.zone.widget.LikeTextView;
import com.efounder.zone.widget.MutiContentDisplayView;
import com.efounder.zone.widget.ThumbsCommentsTransmitView;

import com.utilcode.util.LogUtils;
import com.utilcode.util.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

import static com.efounder.zone.util.ZoneHelperUtil.gotoOtherZone;

/**
 * @author will
 * 动态适配器
 */
public class MainZoneAdapter extends RecyclerView.Adapter implements BGANinePhotoLayout.Delegate, MutiContentDisplayView.ThumbDisplayListener {

    private static final String TAG = "MainZoneAdapter";
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_EMPTY_LAYOUT = 3;

    private static final int TYPE_BODY = 1;

    private static final int TYPE_MESSAGE = 2;

    private Context context;
    private List<TalksBean> items;
    private FragmentManager fragmentManager;
    public static final int JUMP_DETAIL = 2690;
    private onMoreClickListener mMoreClickListener;
    private OnBgImageChangeListener onBgImageChangeListener;
    private OnMessageClickedListener onMessageClickedListener;
    /**
     * 是否显示 银钻 积分
     */
    private boolean isShowIntegral;

    public MainZoneAdapter(Context context, List<TalksBean> items, FragmentManager fragmentManager) {
        this.context = context;
        this.items = items;
        this.fragmentManager = fragmentManager;
        isShowIntegral = EnvSupportManager.isSupportShowIntergral();

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == TYPE_HEADER) {
            View view = LayoutInflater.from(context).inflate(R.layout.mobile_zone_recycler_header, parent, false);
            return new HeaderViewHolder(view);
        } else if (viewType == TYPE_MESSAGE) {
            View view = LayoutInflater.from(context).inflate(R.layout.mobile_zone_item_zone_message, parent, false);
            return new MessageViewHolder(view);
        } else if (viewType == TYPE_EMPTY_LAYOUT) {
            //空布局
            View view = LayoutInflater.from(context).inflate(R.layout.mobile_zone_recycler_empty_layout, parent, false);
            return new EmptyViewHolder(view);
        }
        View view = LayoutInflater.from(context).inflate(R.layout.mobile_zone_item_dynamics_content, parent, false);
        return new BodyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        if (holder.getItemViewType() == TYPE_HEADER) {
            final int userId = items.get(holder.getAdapterPosition()).getObj().getId();
            User topUser = WeChatDBManager.getInstance().getOneUserById(userId);
            LXGlideImageLoader.getInstance().showUserAvatar(context, ((HeaderViewHolder) holder).ivAvatar, topUser.getAvatar());
            //如果有背景图url，则展示
            LXGlideImageLoader.getInstance().displayImage(context, ((HeaderViewHolder) holder).ivBackground,
                    items.get(holder.getAdapterPosition()).getObj().getPostContent(), R.drawable.zone_main_background_light, R.drawable.zone_main_background_light);
            ((HeaderViewHolder) holder).tvId.setText(String.valueOf(items.get(position).getObj().getId()));
            ((HeaderViewHolder) holder).tvName.setText(topUser.getNickName());

            //如果是自己的
            if (items.get(holder.getAdapterPosition()).getObj().getId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
                //更改背景图
                ((HeaderViewHolder) holder).ivBackground.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onBgImageChangeListener != null) {
                            onBgImageChangeListener.onBgImageChange();
                        }
                    }
                });
                //跳转自己的空间
                ((HeaderViewHolder) holder).ivAvatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        gotoOtherZone(context, userId);
                    }
                });
            }
        } else if (holder.getItemViewType() == TYPE_BODY) {

            try {
                final int userId = items.get(holder.getAdapterPosition()).getObj().getPostAuthor();
                final User user = WeChatDBManager.getInstance().getOneUserById(userId, UserEvent.EVENT_ZONE);

                String authorUserName = items.get(holder.getAdapterPosition()).getObj().getAuthorUserName();
                String authorAvatar = items.get(holder.getAdapterPosition()).getObj().getAuthorAvatar();
                if (authorUserName == null) {
                    authorUserName = user.getNickName();
                }
                if (authorAvatar == null || "".equals(authorAvatar)) {
                    authorAvatar = user.getAvatar();
                }
                //昵称
                ((BodyViewHolder) holder).tvName.setText(authorUserName);
                //显示积分
                String integral = "+" + items.get(holder.getAdapterPosition()).getObj().getIntegral() + ResStringUtil.getString(R.string.zone_silver_drill);
                ((BodyViewHolder) holder).mTvScore.setText(integral);
                //时间
                if (items.get(holder.getAdapterPosition()).getObj().getPostCreatetime() != null)
                    LogUtils.e("onBindViewHolder--MainZoneFragment-->" + "----" + Utils.getApp().getResources().getConfiguration().locale.getCountry());

                ((BodyViewHolder) holder).tvTime.setText(ZoneTimeUtil.formatTime(items.get(holder.getAdapterPosition()).getObj().getPostCreatetime()));
                //头像
                LXGlideImageLoader.getInstance().showUserAvatar(context, ((BodyViewHolder) holder).ivAvatar, authorAvatar);
                ((BodyViewHolder) holder).mutiContentDisplayView.setDelegate(MainZoneAdapter.this);
                ((BodyViewHolder) holder).mutiContentDisplayView.setOnLoadFinishLisner(this);

                //设备
                ((BodyViewHolder) holder).tvDeviceType.setText(items.get(holder.getAdapterPosition()).getObj().getDevice());
                //浏览次数、点赞、评论和分享View
                ((BodyViewHolder) holder).thumbsCommentsTransmitView.display(holder.getAdapterPosition(), items.get(holder.getAdapterPosition()), fragmentManager);
                //点赞
                ((BodyViewHolder) holder).likeTextView.setLikeBeanList(items.get(holder.getAdapterPosition()).getLikes());

                // 点赞好友列表点击人的姓名
                ((BodyViewHolder) holder).likeTextView.setListener(new LikeTextView.onItemClickListener() {
                    @Override
                    public void onItemClick(TalksBean.LikesBean bean) {
                        gotoOtherZone(context, bean.getUserId());
                    }
                });
                //评论
                ((BodyViewHolder) holder).mCommentListView.setCommentData(items.get(holder.getAdapterPosition()).getComment());
                ((BodyViewHolder) holder).mCommentListView.setCommentClickListener(new CommentListView.onCommentClickListener() {
                    @Override
                    public void onUserClick(String userId) {
                        // 点击评论的用户名
                        gotoOtherZone(context, Integer.valueOf(userId));
                    }

                    @Override
                    public void onCommentClick(final ZoneCommentBean zoneCommentBean) {
                        if (zoneCommentBean.getCommentUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
                            //自己的评论，点击删除
                            new AlertDialog.Builder(context).setMessage(R.string.zone_confirm_delete).setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //删除评论
                                    CommentUtil.deleteComment(context, holder.getAdapterPosition(), items.get(holder.getAdapterPosition()), zoneCommentBean.getId());
                                }
                            }).setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).show();
                        } else {
                            //回复其他人的评论
                            CommentUtil.sendComment(context, holder.getAdapterPosition(), zoneCommentBean, items.get(holder.getAdapterPosition()), fragmentManager);
                        }

                    }
                });

                //判断content是否为null,null为原说说已经删除
                if (items.get(holder.getAdapterPosition()).getObj().getPostContent() != null) {
                    //文字、图片或视频
                    ((BodyViewHolder) holder).mutiContentDisplayView.display(items.get(holder.getAdapterPosition()).getObj(), true);
                } else {
                    //原说说被删除
                    ((BodyViewHolder) holder).mutiContentDisplayView.sourceContentDeleteStyle((String) items.get(holder.getAdapterPosition()).getObj().getTransmitContent());
                }
                ((BodyViewHolder) holder).ivMore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mMoreClickListener != null) {
                            mMoreClickListener.click(holder.getAdapterPosition(), v);
                        }
                    }
                });
                //头像点击事件,跳转个人空间
                ((BodyViewHolder) holder).ivAvatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        gotoOtherZone(context, userId);
                    }
                });
                //点击进入详情的点击事件
                setJumpToDetailListener(holder);
                //点击评论框评论
                ((BodyViewHolder) holder).llComment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                    sendComment(position, null);
                        CommentUtil.sendComment(context, holder.getAdapterPosition(), null, items.get(holder.getAdapterPosition()), fragmentManager);

                    }
                });
                //是否显示银钻积分
                if (isShowIntegral) {
                    ((BodyViewHolder) holder).llMobileZoneIconJifen.setVisibility(View.VISIBLE);
                } else {
                    ((BodyViewHolder) holder).llMobileZoneIconJifen.setVisibility(View.GONE);
                }

                //积分动画
                Drawable drawable = ((BodyViewHolder) holder).mIvScoreIcon.getDrawable();
                if (drawable != null && drawable instanceof AnimationDrawable) {
                    ((AnimationDrawable) drawable).start();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (getItemViewType(position) == TYPE_MESSAGE) {
            //消息结构
            ((MessageViewHolder) holder).msgNum.setText(String.valueOf(items.get(position).getObj().getLikeCount()));
            ((MessageViewHolder) holder).llContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO: 18-6-29 t跳转消息列表页

                    Intent intent = new Intent(context, ZoneMessageActivity.class);
                    context.startActivity(intent);
                    EnvironmentVariable.setProperty("zone_has_new_message", "0");
                    EventBus.getDefault().post(new SystemInitOverEvent());
                    if (onMessageClickedListener != null) {
                        onMessageClickedListener.onMessageClicked();
                    }
                }
            });
        }
    }

    /**
     * 点击进入详情页面
     *
     * @param holder
     */
    private void setJumpToDetailListener(final RecyclerView.ViewHolder holder) {
        ((BodyViewHolder) holder).mutiContentDisplayView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JumpToDetailActivity(holder.getAdapterPosition());
            }
        });
        ((BodyViewHolder) holder).rlUserInfoContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JumpToDetailActivity(holder.getAdapterPosition());
            }
        });
        ((BodyViewHolder) holder).llDeviceContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JumpToDetailActivity(holder.getAdapterPosition());
            }
        });
        ((BodyViewHolder) holder).thumbsCommentsTransmitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JumpToDetailActivity(holder.getAdapterPosition());
            }
        });
    }

    /**
     * 跳转详情
     *
     * @param position
     */
    private void JumpToDetailActivity(int position) {
        Intent intent = new Intent(context, MobileZoneDetailActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("id", items.get(position).getObj().getId());
        Bundle bundle = new Bundle();
        bundle.putSerializable("talkBean", items.get(position));
        intent.putExtras(bundle);
        ((Activity) context).startActivityForResult(intent, JUMP_DETAIL);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) return TYPE_HEADER;
        //这里用objType = 0来制定为消息类型
        if (items.get(position).getObjType() == -1) {
            //返回空布局
            return TYPE_EMPTY_LAYOUT;
        }
        if (items.get(position).getObjType() == 0) {
            return TYPE_MESSAGE;
        }

        return TYPE_BODY;
    }

    @Override
    public void finish() {
        notifyDataSetChanged();
    }

    public class HeaderViewHolder extends RecyclerView.ViewHolder {
        ImageView ivBackground;//背景图
        CircleImageView ivAvatar;//头像
        TextView tvName;
        TextView tvId;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            MultiLanguageUtil.setApplicationLanguage(Utils.getApp());
            ivBackground = itemView.findViewById(R.id.iv_background);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvName = itemView.findViewById(R.id.tv_name);
            tvId = itemView.findViewById(R.id.tv_fxid);
        }
    }

    public class BodyViewHolder extends RecyclerView.ViewHolder {

        //头像
        RoundImageView ivAvatar;
        //昵称
        TextView tvName;
        //时间
        TextView tvTime;
        //显示点赞数量的View
        LikeTextView likeTextView;
        //设备类型
        TextView tvDeviceType;
        //显示文字，图片，视频，网页的View
        MutiContentDisplayView mutiContentDisplayView;
        //显示评论的View
        CommentListView mCommentListView;
        //最下面的评论框
        LinearLayout llComment;
        //点赞，评论，转发的View
        ThumbsCommentsTransmitView thumbsCommentsTransmitView;
        //头布局（头像，昵称，时间，下拉按钮）
        RelativeLayout rlUserInfoContainer;
        //设备的外层布局
        LinearLayout llDeviceContainer;
        //下拉按钮
        ImageView ivMore;
        LinearLayout llContainer;
        //积分数量
        TextView mTvScore;
        //钻石ImageView
        ImageView mIvScoreIcon;
        LinearLayout llMobileZoneIconJifen;

        public BodyViewHolder(View itemView) {
            super(itemView);
            MultiLanguageUtil.setApplicationLanguage(Utils.getApp());
            llContainer = itemView.findViewById(R.id.mobile_zone_container);
            ivAvatar = itemView.findViewById(R.id.mobile_zone_avatar);
            tvName = itemView.findViewById(R.id.mobile_zone_nickname);
            tvTime = itemView.findViewById(R.id.mobile_zone_time);
            mutiContentDisplayView = itemView.findViewById(R.id.mobile_zone_muticontent_display_view);
            likeTextView = itemView.findViewById(R.id.likeview);
            tvDeviceType = itemView.findViewById(R.id.mobile_zone_device_type);
            thumbsCommentsTransmitView = itemView.findViewById(R.id.mobile_zone_thumbs_comments_container);
            llComment = itemView.findViewById(R.id.ll_comment);
            mCommentListView = itemView.findViewById(R.id.ctv_comment_list);
            rlUserInfoContainer = itemView.findViewById(R.id.mobile_zone_user_info_container);
            llDeviceContainer = itemView.findViewById(R.id.mobile_zone_device);
            ivMore = itemView.findViewById(R.id.mobile_zone_drawer);
            //积分
            mTvScore = itemView.findViewById(R.id.mobile_zone_tv_jifen);
            mIvScoreIcon = itemView.findViewById(R.id.mobile_zone_icon_jifen);
            llMobileZoneIconJifen = itemView.findViewById(R.id.ll_mobile_zone_icon_jifen);
        }
    }

    /**
     * 顶部评论点赞等新消息
     */
    public class MessageViewHolder extends RecyclerView.ViewHolder {

        TextView msgNum;//消息条数
        LinearLayout llContainer;//点击的布局

        public MessageViewHolder(View itemView) {
            super(itemView);
            MultiLanguageUtil.setApplicationLanguage(Utils.getApp());
            msgNum = itemView.findViewById(R.id.tv_number);
            llContainer = itemView.findViewById(R.id.ll_container);
        }
    }

    /**
     * 空布局的viewHolder
     */
    public class EmptyViewHolder extends RecyclerView.ViewHolder {


        public EmptyViewHolder(View itemView) {
            super(itemView);
            MultiLanguageUtil.setApplicationLanguage(Utils.getApp());
        }
    }

    /**
     * 点击查看大图
     *
     * @param ninePhotoLayout
     * @param view
     * @param position
     * @param model
     * @param models
     */
    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        // Intent intent = new Intent(context, ViewPagerActivity.class);
        String[] strings = models.toArray(new String[0]);
//        intent.putExtra("urls", strings);
//        intent.putExtra("position", position);
//
//        //使用元素动画跳转
//        ActivityOptionsCompat options = ActivityOptionsCompat
//                .makeSceneTransitionAnimation((Activity) context, view, "imageItem");
//        ActivityCompat.startActivity(context, intent, options.toBundle());

        ViewPagerActivity.showImageWall(context, strings, position, view);
        // context.startActivity(intent);
    }


    public void setMoreClickListener(onMoreClickListener moreClickListener) {
        this.mMoreClickListener = moreClickListener;
    }

    public interface onMoreClickListener {
        void click(int position, View view);
    }

    public interface OnBgImageChangeListener {
        void onBgImageChange();
    }

    public void setOnBgImageChangeListener(OnBgImageChangeListener onBgImageChangeListener) {
        this.onBgImageChangeListener = onBgImageChangeListener;
    }

    public interface OnMessageClickedListener {
        void onMessageClicked();
    }

    public void setOnMessageClickedListener(OnMessageClickedListener onMessageClickedListener) {
        this.onMessageClickedListener = onMessageClickedListener;
    }
}
